package com.tarena.lbs.basic.service.impl;

import com.tarena.lbs.basic.dao.repository.AreaRepository;
import com.tarena.lbs.basic.pojo.po.AreaPO;
import com.tarena.lbs.basic.pojo.vo.AreaVO;
import com.tarena.lbs.basic.service.AreaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AreaServiceImpl implements AreaService {
    @Resource
    private AreaRepository areaRepository;
    public List<AreaVO> queryProvinces() {
        return areaRepository.queryProvinces();
    }

    public List<AreaVO> queryChildren(Integer parentId) {
        return areaRepository.queryChildren(parentId);
    }

    public List<AreaVO> tree() {
        List<AreaPO> areas = areaRepository.findAll();
        return buildAreaTree(areas);
    }

    List<AreaVO> buildAreaTree(List<AreaPO> areas) {
        // 1. 找出所有省级节点（parent_id == 0 或 null）
        List<AreaVO> rootNodes = areas.stream()
                .filter(area -> area.getParentId() == null || area.getParentId() == 0)
                .map(AreaVO::new)
                .collect(Collectors.toList());

        // 2. 递归或循环构建子节点
        for (AreaVO node : rootNodes) {
            buildChildren(node, areas);
        }

        return rootNodes;
    }

    void buildChildren(AreaVO parent, List<AreaPO> allAreas) {
        List<AreaVO> children = allAreas.stream()
                .filter(area -> area.getParentId() != null && area.getParentId().equals(parent.getId()))
                .map(AreaVO::new)
                .collect(Collectors.toList());

        parent.setChildren(children);

        for (AreaVO child : children) {
            buildChildren(child, allAreas);
        }
    }

}
